package com.liunian.subject.domain.handler.subject;

import com.liunian.subject.common.enums.IsDeletedFlagEnum;
import com.liunian.subject.common.enums.SubjectTypeEnum;
import com.liunian.subject.domain.entity.SubjectInfoBO;
import com.liunian.subject.domain.entity.SubjectOptionBO;
import com.liunian.subject.infra.basic.entity.SubjectMultiple;
import com.liunian.subject.infra.basic.service.SubjectMultipleService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class SubjectMultipleHandler implements SubjectInfoTypeHandler{

    @Resource
    private SubjectMultipleService subjectMultipleService;

    @Override
    public SubjectTypeEnum getSubjectType() {
        return SubjectTypeEnum.MULTIPLE;
    }

    @Override
    public Boolean add(SubjectInfoBO subjectInfoBO) {
        List<SubjectInfoBO.SubjectAnswerBO> option = subjectInfoBO.getOptionList();
        List<SubjectMultiple> multipleList = new ArrayList<>();
        option.forEach(data -> {
            SubjectMultiple subjectMultiple = new SubjectMultiple();
            subjectMultiple.setSubjectId(subjectInfoBO.getId());
            subjectMultiple.setOptionContent(data.getOptionContent());
            subjectMultiple.setOptionType(data.getOptionType());
            subjectMultiple.setIsCorrect(data.getIsCorrect());
            subjectMultiple.setCreatedAt(LocalDateTime.now());
            subjectMultiple.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            multipleList.add(subjectMultiple);
        });
        return subjectMultipleService.saveBatch(multipleList);
    }

    @Override
    public SubjectOptionBO query(long subjectId) {
        List<SubjectMultiple> subjectMultiples = subjectMultipleService.selectMultipleAnswer(subjectId);
        List<SubjectInfoBO.SubjectAnswerBO> answerBOS = new ArrayList<>();
        subjectMultiples.forEach(data -> {
            SubjectInfoBO.SubjectAnswerBO bo = new SubjectInfoBO.SubjectAnswerBO();
            bo.setOptionType(data.getOptionType());
            bo.setOptionContent(data.getOptionContent());
            bo.setIsCorrect(data.getIsCorrect());
            answerBOS.add(bo);
        });
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOption(answerBOS);
        return subjectOptionBO;
    }
}
